package com.seal.commons.generator.db;

import com.seal.commons.generator.config.DatabaseConfig;
import com.seal.commons.generator.vo.TableField;
import com.seal.commons.generator.vo.TableInfo;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 功能描述: <br/>
 *
 * @author yong.huang
 * @date: 2020-08-10 20:36<br/>
 * @since JDK 1.8
 */
@Slf4j
public class MysqlTemplateSql extends AbstractTemplateSql{

    public static final Logger LOGGER = LoggerFactory.getLogger(MysqlTemplateSql.class);

    @Override
    public TableInfo getTable(String tableName, DatabaseConfig databaseConfig ) throws SQLException {
        Connection conn = getConnect(databaseConfig);
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
             stmt = conn.prepareStatement("select COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_TYPE, COLUMN_KEY, COLUMN_COMMENT,ORDINAL_POSITION  from information_schema.columns   where table_name='"+tableName+"' ");
            rs = stmt.executeQuery();
            TableInfo tableInfo = new TableInfo(tableName, "");
            getCloumns(rs, tableInfo);
            return tableInfo;
        } catch (SQLException e) {
            log.error("get tableInfo error", e);
        } finally {
            close(conn, stmt, rs);
        }
        return null;
    }


    /**
     * 加载列
     * @param rs
     * @param tableInfo
     * @throws SQLException
     */
    private void getCloumns(ResultSet rs, TableInfo tableInfo ) throws SQLException {
        while (rs.next()) {
            // 这里没有提供获取当前列是否主键/外键的信息提示
            String columnName = rs.getString("COLUMN_NAME");
            TableField field = new TableField();
            field.setName(columnName);
            field.setType(rs.getString("COLUMN_TYPE"));
            field.setNullable("YES".equals(rs.getString("IS_NULLABLE")));
            field.setComment(rs.getString("COLUMN_COMMENT"));
            field.setIndex(rs.getInt("ORDINAL_POSITION"));
            tableInfo.addFiled(field);

            String columnKey =  rs.getString("COLUMN_KEY");
            if("PRI".equals(columnKey)){
                tableInfo.setPk(columnName);
            }
        }
    }


}